//
//  UIImageView+Extension.swift
//  SinaWeibo
//
//  Created by celeste on 16/5/15.
//  Copyright © 2016年 celeste. All rights reserved.
//

import UIKit
import SDWebImage
extension UIImageView {
    
    convenience init(ld_imageName imageName: String) {
        self.init(image: UIImage(named: imageName))
    }
    
    func ld_setImageWithURL(urlString: String?,
        placeholderName: String?,
        size: CGSize = CGSizeZero,
        isCorner: Bool = false,
        backColor: UIColor? = UIColor.whiteColor()) {
            
            // 占位图像
            var placeholderImage: UIImage?
            
            if placeholderName != nil {
                placeholderImage = UIImage(named: placeholderName!)
            }
            
            // 如果 url 为 nil
            guard let urlString = urlString,
                let url = NSURL(string: urlString) else {
                    // 如果 urlString 为nil，但是指定了占位图像，显示占位图像
                    image = placeholderImage
                    
                    return
            }
            
            // 判断裁切尺寸
            if size == CGSizeZero {
                sd_setImageWithURL(url, placeholderImage: placeholderImage)
                
                return
            }
            
            // 对图像进行裁切，提示：从网络不一定能够获取到图像
            sd_setImageWithURL(url, placeholderImage: placeholderImage) { (image, _, _, _) -> Void in
                
                // 1. 判断图像是否存在，如果没有图像直接返回
                guard let image = image else {
                    return
                }
                
                // 2. 对图像进行裁切
                image.ld_asyncDrawImage(size, isCorner: isCorner, backColor: backColor) { (image) -> () in
                    self.image = image
                }
            }
    }
    
}
